// server.js
const express = require('express');
const { JSDOM } = require('jsdom');
const { SVG, registerWindow } = require('@svgdotjs/svg.js');

const app = express();
const port = 3000;

// 设置 DOM 环境（SVG.js 需要 DOM 环境）
function setupDOM() {
    const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
    global.window = dom.window;
    global.document = dom.window.document;
}

// 初始化 DOM
setupDOM();

registerWindow(window, document);

// 路由1: 基础 SVG 生成
app.get('/svg', (req, res) => {
    const { width = 400, height = 300, text = 'Hello SVG' } = req.query;

    const draw = SVG().size(parseInt(width), parseInt(height));
    
    // 创建渐变背景
    const gradient = draw.gradient('linear', function(add) {
        add.stop(0, '#667eea');
        add.stop(1, '#764ba2');
    });
    
    draw.rect(width, height).fill(gradient);
    
    // 添加文本
    /*draw.text(text)
        .move(50, 150)
        .font({ 
            size: 24, 
            family: 'Arial',
            anchor: 'start',
            fill: '#fff',
        })
        .move(95 + index * 60, 240 - value);*/

        const textElement = draw.plain(text);
        textElement
        .font({ 
            size: 24, 
            fill: '#fff'
        });

        textElement.attr('x', 50);
        textElement.attr('y', 150);
    
    
    // 添加一个圆形装饰
    draw.circle(80)
        .move(300, 50)
        .fill('rgba(255,255,255,0.2)')
        .stroke({ color: '#fff', width: 2 });
    
    // 设置响应头并返回 SVG
    res.setHeader('Content-Type', 'image/svg+xml');
    res.send(draw.svg());
});

// 路由2: 柱状图 SVG
app.get('/chart', (req, res) => {
    const draw = SVG().size(500, 300);
    
    // 简单的柱状图数据
    const data = [30, 60, 90, 120, 150, 180];
    const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD'];
    
    // 添加背景
    draw.rect(500, 300).fill('#f8f9fa');
    
    // 绘制柱状图
    data.forEach((value, index) => {
        draw.rect(40, value)
            .move(80 + index * 60, 250 - value)
            .fill(colors[index])
            .stroke({ color: '#333', width: 1 });
        
        // 添加数值标签
        /*draw.text(value.toString())
            .move(95 + index * 60, 240 - value)
            .font({ size: 12, family: 'Arial', fill: '#333' });*/

        const textElement = draw.plain(value.toString());
        textElement.font({ size: 12, family: 'Arial', fill: '#333' });

        textElement.attr('x', 95 + index * 60);
        textElement.attr('y', 240 - value);
    });
    
    // 添加标题
    /*draw.text('销售数据图表')
        .move(180, 30)
        .font({ size: 20, family: 'Arial', fill: '#333', weight: 'bold' });*/

        const textElement = draw.plain('销售数据图表');
        textElement
        .font({ size: 20, family: 'Arial', fill: '#333', weight: 'bold' });

        textElement.attr('x', 180);
        textElement.attr('y', 30);
    
    res.setHeader('Content-Type', 'image/svg+xml');
    res.send(draw.svg());
});

// 路由3: 饼图 SVG
app.get('/pie', (req, res) => {
    const draw = SVG().size(400, 300);
    
    // 饼图数据
    const data = [
        { value: 40, color: '#FF6B6B', label: '产品 A' },
        { value: 25, color: '#4ECDC4', label: '产品 B' },
        { value: 20, color: '#45B7D1', label: '产品 C' },
        { value: 15, color: '#96CEB4', label: '产品 D' }
    ];
    
    // 绘制饼图
    let currentAngle = 0;
    const total = data.reduce((sum, item) => sum + item.value, 0);
    const centerX = 150;
    const centerY = 150;
    const radius = 80;
    
    data.forEach((item, index) => {
        const angle = (item.value / total) * 360;
        const endAngle = currentAngle + angle;
        
        // 计算弧线路径
        const startRad = (currentAngle - 90) * Math.PI / 180;
        const endRad = (endAngle - 90) * Math.PI / 180;
        
        const x1 = centerX + radius * Math.cos(startRad);
        const y1 = centerY + radius * Math.sin(startRad);
        const x2 = centerX + radius * Math.cos(endRad);
        const y2 = centerY + radius * Math.sin(endRad);
        
        const largeArc = angle > 180 ? 1 : 0;
        
        const pathData = [
            `M ${centerX} ${centerY}`,
            `L ${x1} ${y1}`,
            `A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2}`,
            'Z'
        ].join(' ');
        
        draw.path(pathData).fill(item.color).stroke({ color: '#fff', width: 2 });
        
        currentAngle = endAngle;
    });
    
    // 添加图例
    data.forEach((item, index) => {
        // 图例颜色块
        draw.rect(15, 15)
            .move(250, 80 + index * 25)
            .fill(item.color);
        
        // 图例文本
        /*draw.text(`${item.label}: ${item.value}%`)
            .move(270, 92 + index * 25)
            .font({ size: 12, family: 'Arial', fill: '#333' });*/

        const textElement = draw.plain(`${item.label}: ${item.value}%`);
        textElement
        .font({ size: 12, family: 'Arial', fill: '#333' });

        textElement.attr('x', 270);
        textElement.attr('y', 92 + index * 25);    
    });
    
    res.setHeader('Content-Type', 'image/svg+xml');
    res.send(draw.svg());
});

// 路由4: 首页，显示所有可用路由
app.get('/', (req, res) => {
    res.send(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>SVG.js Express 服务器</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 40px; }
                .link { display: block; margin: 10px 0; padding: 10px; background: #f0f0f0; text-decoration: none; color: #333; border-radius: 5px; }
                .link:hover { background: #e0e0e0; }
            </style>
        </head>
        <body>
            <h1>SVG.js Express 服务器示例</h1>
            <p>点击以下链接查看不同的 SVG 生成示例：</p>
            <a class="link" href="/svg" target="_blank">基础 SVG</a>
            <a class="link" href="/svg?width=600&height=400&text=自定义文本" target="_blank">带参数的基础 SVG</a>
            <a class="link" href="/chart" target="_blank">柱状图</a>
            <a class="link" href="/pie" target="_blank">饼图</a>
        </body>
        </html>
    `);
});

// 启动服务器
app.listen(port, () => {
    console.log(`🚀 SVG 服务器运行在 http://localhost:${port}`);
    console.log(`📊 可用路由:`);
    console.log(`   http://localhost:${port}/ - 首页`);
    console.log(`   http://localhost:${port}/svg - 基础 SVG`);
    console.log(`   http://localhost:${port}/chart - 柱状图`);
    console.log(`   http://localhost:${port}/pie - 饼图`);
});